from datetime import datetime

from typing import Annotated
from fastapi import APIRouter, Depends, BackgroundTasks, Cookie
from fastapi.requests import Request
from fastapi.security import OAuth2PasswordRequestForm

from sanren.utils import get_current_active_user, create_access_token
from sanren.extensions import ExtRedis
from application.config import appSettings
from application.http import models, schemas


router = APIRouter(prefix='/auth', tags=['Auth'])
module_name = '授权'


def update_last_login_info(user, ip='127.0.0.1'):
    # 更新登录时间
    user.updated_at = datetime.now()
    user.save()


@router.post("/login", response_model=schemas.BaseApiOut)
async def login(
    request: Request,
    background_tasks: BackgroundTasks,
    form_data: schemas.LoginForm,
    session_id: Annotated[str | None, Cookie()] = None
):
    """ 登录 """

    a = models.User.get_password_hash('kaoshi4262')
    print(a)

    # redis
    redis = ExtRedis().instance()
    vcode = redis.get(session_id)
    if vcode is None or vcode != form_data.captcha:
        return {'code': 1, 'message': '验证码错误，请确认后再重新提交登录请求.'}

    user = models.User.where('username', form_data.username).first()
    if user is None or not user.check_password(form_data.password):
        return {'code': 1, 'message': '账户密码错误，请确认后再重新提交登录请求.'}

    if user.is_active == 0:
        return {'code': 1, 'message': '该账户已被禁用，请联系管理员.'}

    # 后台更新登录最新信息
    background_tasks.add_task(update_last_login_info, user=user, ip=request.client.host)

    return {
        'data': {
            'token_type': 'Bearer',
            'access_token': await create_access_token(user.serialize(), expires_delta=appSettings.access_token_expire_minutes),
            'expires': appSettings.access_token_expire_minutes * 60,
        }
    }


@router.post("/token")
async def token(
    request: Request,
    background_tasks: BackgroundTasks,
    form_data: OAuth2PasswordRequestForm = Depends(),
):
    print(form_data)
    user = models.User.where('username', form_data.username).first()
    print(user)

    if user is None or not user.check_password(form_data.password):
        return {'code': 1, 'message': '账户密码错误，请确认后再重新提交登录请求.'}

    if user.is_active == 0:
        return {'code': 1, 'message': '该账户已被禁用，请联系管理员.'}

    # 后台更新登录最新信息
    background_tasks.add_task(update_last_login_info, user=user, ip=request.client.host)

    return {
        'token_type': 'Bearer',
        'access_token': await create_access_token(user.serialize(), expires_delta=appSettings.access_token_expire_minutes),
        'expires': appSettings.access_token_expire_minutes * 60,
    }


@router.get('/logout')
async def logout(
    current_user: Annotated[models.User, Depends(get_current_active_user)],
):
    '''
        注销 - 登出
    '''
    return {
        'code': 0,
        'message': 'success',
        'data': {}
    }


@router.get("/test")
async def test(
    current_user: Annotated[models.User, Depends(get_current_active_user)],
):

    current_user.role = [current_user.role.slug]
    print(current_user.role.slug)

    return {'code': 0, 'current_user': current_user.serialize()}
